import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import styles from './Layout.less';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  List,
  Button,
  Modal,
  Tag,
  message,
  DatePicker,
  Radio,
  Upload,
  Icon,
} from 'antd';

import GoodsModal from 'components/Content/GoodsModal';
import { imgPrex } from '../../utils/constData';

const FormItem = Form.Item;
const { CheckableTag } = Tag;
const Search = Input.Search;
const RadioGroup = Radio.Group;
const RadioButton = Radio.Button;

const CreateadvForm = Form.create()(props => {
  const { modalVisible, form, title, advRecord, advId, advUploadProps, advFileList, advModalVisible, advOk, loading } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      advOk(false, fieldsValue, form);
    });
  };

  function disabledDate(current) {
    // Can not select days before today and today
    return current && current < moment().endOf('day');
  }

  return (
    <Modal
      destroyOnClose
      title={advRecord ? '编辑广告' : '添加广告'}
      visible={modalVisible}
      onOk={okHandle}
      confirmLoading={loading}
      onCancel={() => advModalVisible(false)}
    >
      <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} label="advId" style={{ display: 'none' }}>
        {form.getFieldDecorator('advId', {
          initialValue: advId ? advId : null,
          rules: [{ required: true, message: '请输入advId' }],
        })(<Input placeholder="请输入advId" maxLength="10" />)}
      </FormItem>

      {advRecord ?
        <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} label="detailId" style={{ display: 'none' }}>
          {form.getFieldDecorator('advDetailId', {
            initialValue: advRecord ? advRecord.advDetailId : null,
            rules: [{ required: true, message: '请输入detailId' }],
          })(<Input placeholder="请输入detailId" maxLength="10" />)}
        </FormItem>
        :
        null
      }

      <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} label="封面">
        {
          form.getFieldDecorator('name', {
            // valuePropName: 'fileList',
            rules: [{ required: true, message: '请选择封面' }],
            initialValue: advRecord ? (<img src={imgPrex + advRecord.advImg} style={{ width: 30, height: 30 }} />) : null,
          })
            (<Upload
              {...advUploadProps}
            >
              <Button>
                <Icon type="upload" />浏览
         			  </Button>
            </Upload>)}
        {(advRecord && advRecord.detailImg && !(advFileList && (advFileList.length > 0))) ?
          <img src={imgPrex + advRecord.detailImg} style={{ width: 50 }} />
          :
          null
        }
      </FormItem>
      {/* <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} label="goodsId" style={{ display: 'none' }}>
        {form.getFieldDecorator('advId', {
          initialValue: goodsId ? goodsId : null,
          rules: [{ required: true, message: 'advId' }],
        })(<Input placeholder="advId" maxLength="10" />)}
      </FormItem> */}

      <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} label="广告名称" >
        {form.getFieldDecorator('detailName', {
          initialValue: advRecord ? advRecord.detailName : null,
          rules: [{ required: true, message: '广告名称不能为空' }],
        })(<Input placeholder="请输入广告名称" maxLength="10" />)}
      </FormItem>
      <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} label="链接">
        {form.getFieldDecorator('detailUrl', {
          initialValue: advRecord ? advRecord.detailUrl : null,
          rules: [{ required: true, message: '请输入链接' }],
        })(<Input placeholder="请输入链接" maxLength="200" />)}
      </FormItem>
      <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} label="有效期">
        {form.getFieldDecorator('expireTime', {
          rules: [{ required: true, message: '请输入有效期' }],
          initialValue: advRecord ? moment(advRecord.expireTime) : null,
        })(
          <DatePicker disabledDate={disabledDate} />
        )}
      </FormItem>

    </Modal>
  );
});


@connect(({ parentRecomm, loading }) => ({
  parentRecomm,
  loading: loading.models.parentRecomm,
}))
@Form.create()
export default class Adv extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      advDetailList: this.props.advDetailList || [],
      advId: this.props.advId,

      fileList: [],
      file: null,

      advRecord: null,
      modalVisible: false,

      advFileList: [],
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.advDetailList != this.props.advDetailList) {
      this.setState({
        advDetailList: nextProps.advDetailList
      })
    }
  }


  _bookletModalVisible(flag, item) {
    console.log('item bookletrecord', item)
    if (!flag) {
      this.setState({
        advRecord: null,
        modalVisible: flag,

        fileList: [],
        file: null,
      })
    } else {
      this.setState({
        advRecord: item,
        modalVisible: flag,
      })
    }
  }


  _bookletOk(flag, booklet, modalForm) {
    let values = { ...booklet, expireTime: (booklet.expireTime.format('YYYY-MM-DD')), name: this.state.file }

    if (values.advDetailId) {
      this.props.dispatch({
        type: 'parentRecomm/editAdvDetail',
        payload: values,
        callback: (returnData) => this._bookletAddCallback(returnData, modalForm)
      });
    } else {
      this.props.dispatch({
        type: 'parentRecomm/addAdvDetail',
        payload: values,
        callback: (returnData) => this._bookletAddCallback(returnData, modalForm)
      });
    }


  }

  _bookletAddCallback(returnData, modalForm) {
    this.props.advSearch();
    this._bookletModalVisible(false);
    modalForm.resetFields();
  }

  _renderItem(item, i) {
    return (
      <List.Item key={item.bookletId} >
        <Card style={{ marginLeft: '10px', width: '200px' }}

          // style={{ width: '200px' }}
          cover={
            <img style={{ height: '120px' }}
              alt="example"
              src={imgPrex + item.detailImg}
            />
          }
          actions={[
            <Button
              icon="edit"
              size="large"
              onClick={() => {
                this._bookletModalVisible(true, item);
              }}
            >
              编辑
                </Button>,
          ]}
        >
          {/* <Card.Meta title={'链接：' + item.bookletUrl ? item.bookletUrl : '请填写'} /> */}
        </Card>
      </List.Item >
    )
  }

  render() {
    const { advDetailList } = this.state;

    const advUploadProps = {
      // action: '//jsonplaceholder.typicode.com/posts/',
      onRemove: (file) => {
        this.setState(({ fileList }) => {
          const index = fileList.indexOf(file);
          const newFileList = fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
            file: file
          };
        });
      },
      beforeUpload: (file) => {
        this.setState(({ fileList }) => ({
          fileList: [file],
          file: file,
        }));

        return false;
      },
      fileList: this.state.fileList
    };

    return (
      <Card title={'编辑广告运营位'} style={{ width: '760px' }}>
        {advDetailList.length < 5 ?
          <Button type="primary" style={{ marginBottom: '15px' }} onClick={() => this._bookletModalVisible(true, null)} >添加广告运营位</Button>
          :
          null
        }
        <div rowKey="bookletSeq" style={{display:'flex', flexWrap:'wrap'}}>
          {advDetailList.length > 0 ?
            advDetailList.map((item, i) => this._renderItem(item, i))
            :
            null
          }
        </div>



        <CreateadvForm advRecord={this.state.advRecord}
          advModalVisible={(flag) => this._bookletModalVisible(flag)}
          advOk={(flag, booklet, modalForm) => this._bookletOk(flag, booklet, modalForm)}
          advUploadProps={advUploadProps}
          advFileList={this.state.fileList}
          modalVisible={this.state.modalVisible}
          advId={this.state.advId}
          loading={this.props.loading}
        />
      </Card>
    )
  }
}